package leetcode_周赛._2021._202103._20210321;

import java.util.ArrayList;
import java.util.List;

/**
 * @author yzh
 * @data 2021/3/21 10:50
 * 加入采购订单：积压中的销售订单的价格小于采购订单的价格
 * 加入销售订单：积压中的采购订单的价格大于销售订单
 * 思路：
 *   设置两个集合来分别存储积压的采购订单和销售订单
 *   消去订单
 *   相等  把集合中的元素去掉，结束循环
 *   大于  把集合中的元素去掉
 *   小于  把集合中的元素减掉，结束循环
 */
public class _5710 {
    public static void main(String[] args) {
        int[][] orders = new int[][]{{10,5,0},{15,2,1},{25,1,1},{30,4,0}};
        System.out.println(new _5710().getNumberOfBacklogOrders(orders));
    }

    public int getNumberOfBacklogOrders(int[][] orders) {
        List<int[]> buys = new ArrayList<>(), sells = new ArrayList<>();
        for (int i = 0; i < orders.length; i++) {
            if (orders[i][2] == 0) {
                if (sells.size() == 0) {
                    buys.add(orders[i]);
                } else {
                    List<Integer> index = new ArrayList<>();
                    for (int x = 0; x < sells.size(); x++) {
                        if (orders[i][0] >= sells.get(x)[1]) {
                            orders[i][1] -= sells.get(x)[1];
                            if (orders[i][1] >= 0) {
                                index.add(x);
                            } else {
                                sells.get(x)[1] -= orders[i][1];
                            }
                            if (orders[i][1] <= 0) break;
                        }
                    }
                    for (int i1 = 0; i1 < index.size(); i1++) {
                        sells.remove(index.get(i1));
                    }
                    if (orders[i][1] > 0) buys.add(orders[i]);
                }
            }
            if (orders[i][2] == 1) {
                if (buys.size() == 0) {
                    sells.add(orders[i]);
                } else {
                    List<Integer> index = new ArrayList<>();
                    for (int x = 0; x < buys.size(); x++) {
                        if (orders[i][0] <= buys.get(x)[1]) {
                            orders[i][1] -= buys.get(x)[1];
                            if (orders[i][1] >= 0) {
                                index.add(x);
                            } else {
                                buys.get(x)[1] -= orders[i][1];
                            }
                            if (orders[i][1] <= 0) break;
                        }
                    }
                    for (int i1 = 0; i1 < index.size(); i1++) {
                        buys.remove(index.get(i1));
                    }
                    if (orders[i][1] > 0) sells.add(orders[i]);
                }
            }
        }
        return (buys.size() + sells.size()) % ((int)Math.pow(10, 9) + 7);
    }
}
